/*
 * Create:      柿子
 * CreateDate:  2022/08/22
 * Describe：   配镜申请单
 * */
import React, { Component } from 'react';
import { Row, Col, Card, Button, Input, Tag, Menu, Radio, message, Popconfirm, Modal, Tooltip, Empty, Select } from 'antd';
import { Util } from 'tools';
import { $loadTemplate } from 'pages/lodop/Common/Print.js';
import store from 'store';
import WeChatPayment from './WeChatPayment';
import DynamicRenderingForm from 'pages/common/DynamicRenderingForm';
import PatientAdmOrderCharges from 'pages/Cashier/Report/PatientAdmOrderCharges';
import iconListVisits from 'assets/images/icon_listvisits.png';
import 'pages/workstation/style/CMOrderSave.less'; // 是否计费图标

class GlassesMatchingApplicationForm extends Component {
  constructor(props) {
    super(props);
    var currentPatData = React.$getSessionData('titleData');
    this.state = {
      selectData: {},
      currentPatData,
      leftEyeFormData: [],
      leftRowData: {},
      rightEyeFormData: [],
      rightRowData: {},
      currentEyeCard: 'right', // 当前所在配镜参数card
      brandSelectedKeys: [],
      brandData: [],
      varietiesData: [], // 品种数据
      varieties: undefined,
      varietiesVal: undefined,
      paymentMethod: undefined, // 收款方式
      prePayAmt: '', // 预交金
      optoSourceID: undefined, // 来源渠道
      remark: undefined, // 备注
      fittingRemark: undefined, // 验光
      applicationList: [], // 申请单列表
      currentApplicationID: '', // 申请单ID
      currentApplicationData: {}, // 申请单列表选择操作
      varietyID: '', // 品种选择
      depositAmt: 0, // 预交金余额
      discountVisible: false, // 优惠弹窗
      medSubCatID: undefined,
    }
  }

  componentDidMount() {
    this.getSelectData();
    this.getBrandData('Y');
    this.getApplicationList('', 'N');
    window.addEventListener('keydown', this.handleWidowKeyDown)
  }

  componentWillUnmount() {
    this.setState = (state, callback) => { return; }
    window.removeEventListener('keydown', this.handleWidowKeyDown)
  }

  // 获取初始化数据
  getSelectData = async () => {
    try {
      let res = await React.$asyncPost(this, '17030080');
      this.setState({ selectData: res?.result || {} });
    } catch (error) {
      console.log(error);
    }
  }

  // 整个界面监听键盘事件
  handleWidowKeyDown = (e) => {
    var event = window.event || e;
    event?.stopPropagation();
    if (event.keyCode === 9) {
      event?.preventDefault();
      let { currentEyeCard } = this.state;
      this.handleEyeCardClick(currentEyeCard === 'left' ? 'right' : 'left');
    }
  }

  // 配镜参数左右眼选择
  handleEyeCardClick = (type, trigger) => {
    this.setState({ currentEyeCard: type }, () => {
      this.handleEyeFirstInputFocus('', trigger);
    })
  }

  // 当前所在的眼别输入域获取焦点
  handleEyeFirstInputFocus = (isCurrentFocus, trigger) => {
    let { currentEyeCard } = this.state;
    if (!(this.state[currentEyeCard + 'RowData'] && this.state[currentEyeCard + 'RowData'].focus) || isCurrentFocus === 'Y') { // 已经获取焦点就不用了重新获取焦点了
      let dataIndex = this.state[currentEyeCard + 'EyeFormData'] && this.state[currentEyeCard + 'EyeFormData'].length > 1 && this.state[currentEyeCard + 'EyeFormData'][1].dataIndex;
      this.state[currentEyeCard + 'RowData'].focus = true;
      this.state[(currentEyeCard === 'left' ? 'right' : 'left') + 'RowData'].focus = false; // 另一个眼别焦点置灰
      trigger === 'click' ? '' : this[currentEyeCard + 'EyeFormData' + dataIndex]?.focus();
      let brandID = this.state[currentEyeCard + 'RowData'] && 'brandID' in this.state[currentEyeCard + 'RowData'] ? this.state[currentEyeCard + 'RowData'].brandID : '';
      let varietiesRecord = this.state[currentEyeCard + 'RowData'] && 'varietiesRecord' in this.state[currentEyeCard + 'RowData'] ? this.state[currentEyeCard + 'RowData'].varietiesRecord : {}
      if (brandID) {
        this.setState({ brandSelectedKeys: [brandID] }, () => {
          this.getVarietiesData(brandID);
        });
      }
      this.setState({ varietyID: varietiesRecord?.medID || '' });
    };
  }

  // 获取品牌和品种
  getBrandData = async (isGetFormData) => {
    try {
      let { varietiesVal, medSubCatID } = this.state;
      let data = {
        params: [{
          stkSubCatID: medSubCatID,
          desc: varietiesVal
        }]
      }
      let res = await React.$asyncPost(this, '17030005', data);
      let brandData = res?.result || [];
      this.setState({ brandData }, () => {
        this.handleDefaultFirstBrand(isGetFormData);
      });
    } catch (error) {
      // this.setState({ brandData: [] });
      console.log(error);
    }
  }

  // 默认选择第一个品牌，根据品牌查询品种数据
  handleDefaultFirstBrand = (isGetFormData) => {
    let { brandData } = this.state;
    if (brandData && brandData.length > 0) {
      let brandSelectedKeys = [], brandID = '';
      if (brandData && brandData.length > 0) {
        brandID = brandData[0] && brandData[0].brandID ? String(brandData[0].brandID) : '';
        brandSelectedKeys.push(brandID);
      }
      this.state['leftRowData'].brandID = brandID;
      this.state['rightRowData'].brandID = brandID;
      this.setState({ brandSelectedKeys }, () => {
        this.getVarietiesData(brandID, '', isGetFormData);
      })
    } else {
      this.setState({ varietiesData: [] })
    }
  }

  // 品牌选择
  handleBrandMenuSelect = ({ selectedKeys }) => {
    let brandID = selectedKeys && selectedKeys.length > 0 ? selectedKeys[0] : '';
    this.setState({ brandSelectedKeys: selectedKeys }, () => {
      this.getVarietiesData(brandID);
    })
  }

  // 获取配镜申请单配置
  getApplicationFormData = async (brandID, eyeCard, isFocus, defaultVarietyID) => {
    try {
      const { varietyID, varietiesData } = this.state;
      let varietyRecord = Util.returnDataCccordingToAttributes(varietiesData, defaultVarietyID || varietyID, 'medID');
      let data = {
        params: [{
          brandID,
          stockID: varietyRecord?.stockID || ''
        }]
      }
      let res = await React.$asyncPost(this, '17030006', data);
      let applicationFormData = Util.addKeyValueToDataSource(res?.result?.rows || [], false, 0).filter(item => item.display === 'Y');
      (!eyeCard || eyeCard === 'left') ? this.getEyeFormData('leftEyeFormData', applicationFormData, isFocus) : '';
      (!eyeCard || eyeCard === 'right') ? this.getEyeFormData('rightEyeFormData', applicationFormData, isFocus) : '';
    } catch (error) {
      console.log(error);
    }
  }

  // 获取左眼表单数据
  getEyeFormData = (dataIndex, formData, isFocus) => {
    const initFormData = [{
      dataIndex: 'product',
      placeholder: '请先在右侧选中产品',
      title: '配镜产品', //  + '(' + (dataIndex === 'leftEyeFormData' ? 'OS' : 'OD') + ')'
      typeCode: 'TextArea',
      required: 'Y',
      disabled: 'Y',
      col: 24
    }
      // ,
      // {
      //   dataIndex: 'price',
      //   placeholder: '请输入价格',
      //   title: '价格' + '(' + (dataIndex === 'leftEyeFormData' ? 'OS' : 'OD') + ')',
      //   typeCode: 'InputNumber',
      //   required: 'Y',
      //   col: 24,
      //   addonAfter: (
      //     <Tooltip title="元">
      //       <span className="ellipsis" style={{ color: '#666', width: '36px', display: 'block' }}>元</span>
      //     </Tooltip>
      //   ),
      //   onPressEnter: () => this.handleFormItemPressEnter(dataIndex, 0, {}, formData),
      // }
    ];
    formData = formData && formData.map((item, index) => {
      return {
        ...item,
        dataIndex: item.code,
        title: item.descripts, //  + '(' + (dataIndex === 'leftEyeFormData' ? 'OS' : 'OD') + ')'
        typeCode: item?.componentTypeCode || 'Input', // 测试上传
        required: item.required,
        disabled: item.readOnly,
        detailItem: item?.selectData || [],
        defaultValue: undefined,
        min: item?.minxValue || '',
        max: item?.maxValue || '',
        doubt: item?.inputTip || '', // 输入域描述
        errorMsg: item?.errorTip || '', // 校验错误提示
        className: item?.linkClass || '', // 关联类
        addonAfter: (
          item.unitDesc !== 'none' ? (
            <Tooltip title={item.unitDesc || '单位'}>
              <span className="ellipsis" style={{ color: item.unitDesc ? '#666' : '#d9d9d9', width: '36px', display: 'block' }}>{item.unitDesc || '单位'}</span>
            </Tooltip>
          ) : ''
        ),
        col: Number(item?.seatSize || 24), // 一行为24份
        // onRef: ref => this[item.code + dataIndex] = ref,
        onRef: (ref) => this.handleFormItemRef(ref, dataIndex, item.code),
        onPressEnter: item.componentTypeCode !== 'Select' ? () => this.handleFormItemPressEnter(dataIndex, index + 1, item, formData) : '',
        onSelect: item.componentTypeCode === 'Select' ? () => this.handleFormItemPressEnter(dataIndex, index + 1, item, formData) : '',
        changeCallBack: item.componentTypeCode === 'InputNumber' ? () => { } : '',
        callBackResult: item.componentTypeCode === 'InputNumber' ? 'InputNumber' : '',
        onClick: () => this.handleFormItemClick(dataIndex === 'leftEyeFormData' ? 'left' : 'right')
      }
    });
    formData = [...initFormData, ...formData];
    this.state[dataIndex] = formData;
    this.setState({}, () => {
      isFocus === 'N' ? '' : this.handleEyeFirstInputFocus();
    });
  }

  // 输入域点击事件，用于判断是否已选择产品
  handleFormItemClick = (currentEyeCard) => {
    let values = this[currentEyeCard + 'EyeFormRef'] && this[currentEyeCard + 'EyeFormRef'].getFieldsValue();
    if (!(values && values.product)) {
      message.info('请您先选择配镜产品！');
    }
  }

  handleFormItemRef = (ref, dataIndex, code) => {
    let refName = dataIndex + code;
    this[refName] = ref;
  }

  // 输入域回车切换到下一个输入域
  handleFormItemPressEnter = (dataIndex, index, record, dataSource) => {
    if (record && 'enterJumpTo' in record && record.enterJumpTo) {
      index = Util.returnDataCccordingToAttributes(dataSource, record.enterJumpTo, 'productBrandOrderSetID')?.key; // 获取维护对应跳转输入域的下标
    }
    if (this.state[dataIndex] && this.state[dataIndex].length - 1 > index) {
      let nextDataIndex = this.state[dataIndex][index + 1] && this.state[dataIndex][index + 1].dataIndex;
      this[dataIndex + nextDataIndex]?.focus();
    }
    // 修改加急标志/加急标志修改如果是同一个品牌的话就一起修改掉
    if (record?.code === 'Urgent') { // 加急标志
      let currentEyeCard = dataIndex && dataIndex.indexOf('right') > -1 ? 'right' : 'left';
      this.handleUrgentModify(currentEyeCard)
    }
  }

  // 修改加急标志
  handleUrgentModify = (currentEyeCard) => {
    let { leftRowData, rightRowData } = this.state;
    if (leftRowData?.brandID === rightRowData?.brandID) { // 同一品牌加急标志保持一致
      let value = this[currentEyeCard + 'EyeFormRef'] && this[currentEyeCard + 'EyeFormRef'].getFieldsValue();
      let opposeEyeCard = currentEyeCard === 'left' ? 'right' : 'left';
      this[opposeEyeCard + 'EyeFormRef'] && this[opposeEyeCard + 'EyeFormRef'].setFieldsValue({
        Urgent: value?.Urgent || undefined
      });
    }
  }

  // 获取品种数据
  getVarietiesData = (brandID, type, isGetFormData) => {
    let { brandData } = this.state;
    let varietiesData = [];
    for (var i = 0; i < brandData.length; i++) {
      if (String(brandData[i].brandID) === brandID) {
        varietiesData = brandData[i].subArr;
        break;
      }
    }
    if (type === 'get') {
      return varietiesData;
    } else {
      this.setState({ varietiesData }, () => {
        if (isGetFormData === 'Y' && varietiesData && varietiesData.length > 0) { // 默认选择第一个
          this.getApplicationFormData(brandID, '', 'N', varietiesData[0]?.medID || '');
        }
      });
    }
  }

  // 品种选择
  handleVarietiesChange = (e) => {
    const { currentEyeCard, brandSelectedKeys } = this.state;
    let varietyID = e.target.value;
    if (currentEyeCard) {
      let rowData = this.state[currentEyeCard + 'RowData'];
      console.log(currentEyeCard + 'RowData', rowData)
      let brandID = brandSelectedKeys && brandSelectedKeys.length > 0 ? brandSelectedKeys[0] : '';
      let varietiesRecord = rowData && rowData.varietiesRecord ? rowData.varietiesRecord : {};
      if (varietiesRecord && varietiesRecord.varietyID && (varietiesRecord.varietyID === varietyID)) {
        this.setState({
          varietyID: varietyID
        })
        return;
      };
      if (varietiesRecord && varietiesRecord.stockID) {
        Modal.confirm({
          title: '产品切换提醒',
          content: brandID !== rowData.brandID ? '不同品牌产品切换将导致配镜参数清空，是否继续？' : '配镜参数（' + (currentEyeCard === 'left' ? '左眼' : '右眼') + '）已选择产品，确定切换吗？',
          okText: brandID !== rowData.brandID ? '是' : '确认',
          cancelText: brandID !== rowData.brandID ? '否' : '取消',
          onOk: () => {
            this.handleVarietiesConfirm(varietyID);
          },
          onCancel: () => { },
        });
      } else {
        this.handleVarietiesConfirm(varietyID);
      }
    } else {
      message.error("请选择眼别(左眼/右眼)");
    }
  }

  // 确认选择产品
  handleVarietiesConfirm = (varietyID, isFocus) => {
    const { currentEyeCard, brandSelectedKeys } = this.state;
    let brandID = brandSelectedKeys && brandSelectedKeys.length > 0 ? brandSelectedKeys[0] : '';
    let rowData = this.state[currentEyeCard + 'RowData'];
    // 切换了品牌需要重置表单 - 表单内容根据品牌ID查询
    if (brandID !== rowData.brandID) {
      currentEyeCard === 'left' ? this.handleLeftFormReset() : this.handleRightFormReset(); // 重置表单数据
    }
    this.setState({
      varietyID
    }, () => {
      this.setProductValue();
      this.getApplicationFormData(brandID, isFocus === 'N' ? '' : currentEyeCard, isFocus)
    });
  }

  // 选择品牌带入到眼别中
  setProductValue = () => {
    const { varietiesData, varietyID, currentEyeCard, leftRowData, rightRowData, brandSelectedKeys } = this.state;
    let brandID = brandSelectedKeys && brandSelectedKeys.length > 0 ? brandSelectedKeys[0] : '';
    let dataIndex = currentEyeCard + 'RowData';
    let varietiesRecord = {};
    for (var i = 0; i < varietiesData.length; i++) {
      if (varietiesData[i].medID === varietyID) {
        varietiesRecord = varietiesData[i];
        break
      }
    }
    varietiesRecord.varietyID = varietyID;
    this[currentEyeCard + 'EyeFormRef'] && this[currentEyeCard + 'EyeFormRef'].setFieldsValue({
      product: varietiesRecord?.medDesc + '；1片；' + varietiesRecord?.price + '元；',
      price: varietiesRecord?.price || 0
    });
    // console.log("varietiesRecord?.medDesc + '；1片；' + varietiesRecord?.price + '元；'", varietiesRecord?.medDesc + '；1片；' + varietiesRecord?.price + '元；')
    this.state[dataIndex]['brandID'] = brandID;
    this.state[dataIndex]['varietiesRecord'] = varietiesRecord;
    this.setState({ prePayAmt: (Number(leftRowData?.varietiesRecord?.price || 0)) + (Number(rightRowData?.varietiesRecord?.price || 0)) }, () => {
      this.handleEyeFirstInputFocus('Y');
      setTimeout(() => {
        this.handleUrgentModify(currentEyeCard === 'left' ? 'right' : 'left');
      }, 300)
    });
  }

  // 过滤品种数据
  handleFilterVarietiesData = () => {
    let { varietiesData, varietiesVal } = this.state;
    varietiesVal = varietiesVal || '';
    if (varietiesData && Array.isArray(varietiesData)) {
      return varietiesData && varietiesData.filter(item => item?.medDesc?.indexOf(varietiesVal) >= 0);
    }
    return [];
  }

  // 申请单列表选择操作
  handleApplicationListItemClick = (item, type) => {
    let { currentApplicationID } = this.state;
    if ((currentApplicationID !== item.glassesRequestID) || (type === 'save')) {
      this.setState({ currentApplicationID: item.glassesRequestID, currentApplicationData: { ...item } }, () => {
        this.getApplicationDetailData(type);
      })
    } else {
      this.handleReset();
    }
  }

  // 获取配镜申请单详细
  getApplicationDetailData = async (type) => {
    try {
      const { currentApplicationID } = this.state;
      let data = {
        params: [{
          glassesRequestID: currentApplicationID
        }]
      }
      let res = await React.$asyncPost(this, '17030008', data);
      // 左眼
      let leftEye = res.result?.leftEye || [];
      let leftOrderSet = res.result?.leftOrderSet || [];
      let leftBrandID = res.result && res.result.leftBrandID ? res.result.leftBrandID : '';
      let leftVarietiesData = this.getVarietiesData(leftBrandID, 'get');
      let leftStockItemID = res.result?.leftStockItemID || '';
      let leftRowData = {
        product: res.result?.leftProjectDesc,
        valueData: leftEye,
        varietiesRecord: {
          price: res.result?.leftPrice || 0,
          stockID: leftStockItemID,
          medID: leftStockItemID ? Util.returnDataCccordingToAttributes(leftVarietiesData, leftStockItemID, 'stockID')?.medID : ''
        }
      };
      if (leftEye && Array.isArray(leftEye)) {
        for (var i = 0; i < leftEye.length; i++) {
          let leftTypeCode = leftOrderSet && leftOrderSet.length > 0 ? Util.returnDataCccordingToAttributes(leftOrderSet, leftEye[i].fieldCode, 'code')?.componentTypeCode : '';
          leftRowData[leftEye[i].fieldCode] = leftTypeCode === 'Select' ? leftEye[i].reqFieldValueID : leftEye[i].reqFieldValue;
        }
      }
      // 右眼
      let rightEye = res.result?.rightEye || [];
      let rightOrderSet = res.result?.rightOrderSet || [];
      let rightBrandID = res.result && res.result.rightBrandID ? res.result.rightBrandID : '';
      let rightVarietiesData = this.getVarietiesData(rightBrandID, 'get');
      let rightStockItemID = res.result?.rightStockItemID || '';
      let rightRowData = {
        product: res.result?.rightProjectDesc,
        valueData: rightEye,
        varietiesRecord: {
          price: res.result?.rightPrice || 0,
          stockID: res.result?.rightStockItemID,
          medID: rightStockItemID ? Util.returnDataCccordingToAttributes(rightVarietiesData, rightStockItemID, 'stockID')?.medID : ''
        }
      }
      if (rightEye && Array.isArray(rightEye)) {
        for (var i = 0; i < rightEye.length; i++) {
          let rightTypeCode = rightOrderSet && rightOrderSet.length > 0 ? Util.returnDataCccordingToAttributes(rightOrderSet, rightEye[i].fieldCode, 'code')?.componentTypeCode : '';
          rightRowData[rightEye[i].fieldCode] = rightTypeCode === 'Select' ? rightEye[i].reqFieldValueID : rightEye[i].reqFieldValue;
        }
      }
      let currentEyeCard = ((leftEye && leftEye.length > 0) || !(rightEye && rightEye.length > 0)) ? 'left' : 'right';
      let brandID = currentEyeCard === 'left' ? leftBrandID : rightBrandID;
      let brandSelectedKeys = brandID ? [brandID] : [];
      let varietiesRecord = currentEyeCard === 'left' ? (leftRowData?.varietiesRecord || {}) : (rightRowData?.varietiesRecord || {});
      this.setState({
        prePayAmt: res.result && 'prePayAmt' in res.result ? res.result.prePayAmt : undefined, // 预交金
        leftRowData,
        rightRowData,
        currentEyeCard: type === 'save' ? this.state.currentEyeCard : currentEyeCard,
        brandSelectedKeys,
        varietyID: varietiesRecord?.medID || '',
        optoSourceID: res.result?.optoSourceID || undefined, // 来源渠道
        remark: res.result?.remark || undefined, // 备注
        fittingRemark: res.result?.fittingRemark || undefined, // 开单备注
      }, () => {
        this.getVarietiesData(brandID);
        this.getEyeFormData('leftEyeFormData', Util.addKeyValueToDataSource(leftOrderSet, false, 0), 'N');
        this.getEyeFormData('rightEyeFormData', Util.addKeyValueToDataSource(rightOrderSet, false, 0), 'N');
      })
    } catch (error) {
      console.log(error);
    }
  }

  // 重置左眼表单数据
  handleLeftFormReset = () => {
    const { leftRowData, currentApplicationID, brandSelectedKeys } = this.state;
    let brandID = brandSelectedKeys && brandSelectedKeys.length > 0 ? brandSelectedKeys[0] : '';
    if (currentApplicationID) {
      this.setState({
        leftRowData: {
          brandID,
          product: leftRowData?.leftRowData || '',
          varietiesRecord: leftRowData?.varietiesRecord || '',
        }
      })
    } else {
      this.leftEyeFormRef && this.leftEyeFormRef.resetFields();
      this.setState({
        leftRowData: {
          brandID
        }
      })
    }
  }

  // 重置右眼表单数据
  handleRightFormReset = () => {
    const { rightRowData, currentApplicationID, brandSelectedKeys } = this.state;
    let brandID = brandSelectedKeys && brandSelectedKeys.length > 0 ? brandSelectedKeys[0] : '';
    if (currentApplicationID) {
      this.setState({
        rightRowData: {
          brandID,
          product: rightRowData?.rightRowData || '',
          varietiesRecord: rightRowData?.varietiesRecord || '',
        }
      })
    } else {
      this.rightEyeFormRef && this.rightEyeFormRef.resetFields();
      this.setState({
        rightRowData: {
          brandID
        }
      });
    }
  }

  // 点击建议预交金额设置预交金额
  handleSetPrePayAmt = () => {
    let { leftRowData, rightRowData } = this.state;
    let prePayAmt = ((Number((leftRowData?.varietiesRecord?.price || 0)).toFixed(3)) * 1000 + (Number((rightRowData?.varietiesRecord?.price || 0)).toFixed(3)) * 1000) / 1000;
    this.setState({ prePayAmt });
  }

  // 同右眼
  handleSameRightEye = () => {
    this.handleLeftFormReset(); // 重置左眼表单数据
    let { rightEyeFormData, rightRowData } = this.state;
    let rightValues = this.rightEyeFormRef && this.rightEyeFormRef.getFieldsValue();
    let formData = rightEyeFormData ? JSON.parse(JSON.stringify(rightEyeFormData)).splice(1) : [];
    this.getEyeFormData('leftEyeFormData', formData);
    let leftRowData = { ...rightRowData, ...rightValues };
    this.setState({ leftRowData, prePayAmt: (Number(leftRowData?.varietiesRecord?.price || 0)) + (Number(rightRowData?.varietiesRecord?.price || 0)) })
  }

  // 同左眼
  handleSameLeftEye = () => {
    this.handleRightFormReset(); // 重置右眼表单数据
    let { leftEyeFormData, leftRowData } = this.state;
    let leftValues = this.leftEyeFormRef && this.leftEyeFormRef.getFieldsValue();
    let formData = leftEyeFormData ? JSON.parse(JSON.stringify(leftEyeFormData)).splice(1) : [];
    this.getEyeFormData('rightEyeFormData', formData);
    let rightRowData = { ...leftRowData, ...leftValues };
    this.setState({ rightRowData, prePayAmt: (Number(leftRowData?.varietiesRecord?.price || 0)) + (Number(rightRowData?.varietiesRecord?.price || 0)) })
  }

  // 获取申请单列表
  getApplicationList = async (saveID, isReset) => {
    try {
      let { currentPatData } = this.state;
      if (!(currentPatData && currentPatData.admID)) return;
      let data = {
        params: [{
          admID: currentPatData?.admID || ''
        }]
      }
      let res = await React.$asyncPost(this, '17030007', data);
      let applicationList = res?.result?.rows || [];
      this.setState({ applicationList, depositAmt: res.result?.depositAmt || 0 }, () => {
        if (saveID) {
          let saveItem = Util.returnDataCccordingToAttributes(this.state.applicationList, saveID, 'glassesRequestID')
          this.handleApplicationListItemClick(saveItem, 'save');
          setTimeout(() => {
            var gundong = document.getElementById('gmaf-application-list-content');
            gundong.scrollTop = gundong.scrollHeight;
          }, 100)
        } else {
          isReset !== 'N' && this.handleReset();
        }
      })
    } catch (error) {
      console.log(error);
    }
  }

  // 保存
  handleSave = async (fn) => {
    try {
      let { currentApplicationID, currentPatData, leftEyeFormData, rightEyeFormData, leftRowData, rightRowData, prePayAmt, optoSourceID, remark, fittingRemark, selectData } = this.state;
      if (!(currentPatData && currentPatData.admID)) return;
      if (prePayAmt === undefined || prePayAmt === '') {
        message.error('请输入预交金额。');
        return;
      }
      if (!optoSourceID && selectData?.channelSourceNotMust !== 'Y') {
        message.error('验配渠道不能为空。');
        return;
      }
      let eyeSaveFlag = true;
      let leftFormValues = {};
      let leftVarietiesRecord = leftRowData && leftRowData.varietiesRecord ? leftRowData.varietiesRecord : {};
      if (leftVarietiesRecord && leftVarietiesRecord.stockID) { // 左眼
        eyeSaveFlag = false;
        leftFormValues = await this.leftEyeFormRef.handleSave();
        if (leftFormValues && leftFormValues.error) {
          message.error('请完善左眼必填信息。');
          return;
        }
      }
      let rightFormValues = {};
      let rightVarietiesRecord = rightRowData && rightRowData.varietiesRecord ? rightRowData.varietiesRecord : {};
      if (rightVarietiesRecord && rightVarietiesRecord.stockID) { // 右眼
        eyeSaveFlag = false;
        rightFormValues = await this.rightEyeFormRef.handleSave();
        if (rightFormValues && rightFormValues.error) {
          message.error('请完善右眼必填信息。');
          return;
        }
      }
      if (eyeSaveFlag) {
        message.error('眼别（左眼/右眼）不能同时为空');
        return;
      }
      let data = {
        params: [{
          admID: currentPatData?.admID || '', // 就诊ID
          glassesRequestID: currentApplicationID,
          prePayAmt, // 预交金
          optoSourceID, // 来源渠道
          remark, // 备注
          fittingRemark, // 开单备注
          queID: currentPatData?.queID || '',
          areaRoomID: currentPatData?.areaRoomID || '',
          leftPrice: leftVarietiesRecord && 'price' in leftVarietiesRecord ? leftVarietiesRecord.price : '',
          leftStockItemID: leftVarietiesRecord?.stockID || '',
          leftEye: this.handleCombineFormData(leftFormValues, leftEyeFormData, leftRowData?.valueData || []),
          rightPrice: rightVarietiesRecord && 'price' in rightVarietiesRecord ? rightVarietiesRecord.price : '',
          rightStockItemID: rightVarietiesRecord?.stockID || '',
          rightEye: this.handleCombineFormData(rightFormValues, rightEyeFormData, rightRowData?.valueData || [])
        }]
      }
      let res = await React.$asyncPost(this, '17030009', data);
      if (fn) {
        fn && fn();
      } else {
        this.getApplicationList(res.result);
        message.success(res.errorMessage || '保存成功');
        let modifyFlag = this.whetherTheContentIsModified();
        if (modifyFlag === 'all') {
          this.handleUpdateRowData(leftFormValues, 'leftRowData');
          this.handleUpdateRowData(rightFormValues, 'rightRowData');
        } else if (modifyFlag === 'left') {
          this.handleUpdateRowData(leftFormValues, 'leftRowData');
        } else if (modifyFlag === 'right') {
          this.handleUpdateRowData(rightFormValues, 'rightRowData');
        }
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 更新眼别数据
  handleUpdateRowData = (values, dataIndex) => {
    let rowData = this.state[dataIndex];
    for (var rowKey in rowData) {
      for (var valKey in values) {
        if ((rowKey === valKey) && (rowData[rowKey] !== values[valKey])) {
          this.state[dataIndex][rowKey] = values[valKey];
        }
      }
    }
    this.setState({})
  }

  // 获取动态眼别表单数据
  handleCombineFormData = (values, dataSource, valueData) => {
    let combineFormData = [];
    if (dataSource && dataSource.length > 0) {
      for (var i = 0; i < dataSource.length; i++) {
        for (var keys in values) {
          if ((dataSource[i].dataIndex === keys) && (dataSource[i].dataIndex !== 'product')) {
            combineFormData.push({
              glassesReqDetailID: valueData && valueData.length > 0 ? Util.returnDataCccordingToAttributes(valueData, keys, 'fieldCode')?.glassesReqDetailID : undefined,
              reqFieldID: dataSource[i].productBrandOrderSetID,
              reqFieldValue: dataSource[i].typeCode === 'Select' ? Util.returnDataCccordingToAttributes(dataSource[i].selectData, values[keys])?.descripts : values[keys],
              reqFieldValueID: dataSource[i].typeCode === 'Select' ? values[keys] : undefined,
            })
          }
        }
      }
    }
    return combineFormData;
  }

  // 清空数据
  handleReset = () => {
    this.setState({
      currentApplicationID: '',
      currentApplicationData: {},
      prePayAmt: undefined,
      leftRowData: {},
      rightRowData: {},
      varietyID: '',
      brandSelectedKeys: [],
      optoSourceID: undefined,
      remark: undefined,
      fittingRemark: undefined,
    }, () => {
      this.handleLeftFormReset();
      this.handleRightFormReset();
      this.handleDefaultFirstBrand('Y');
    })
  }

  // 更新配镜申请单状态
  handleModifyStatus = async (statusCode) => {
    try {
      let { currentApplicationID } = this.state;
      let data = {
        params: [{
          glassesRequestID: currentApplicationID,
          statusCode
        }]
      }
      let res = await React.$asyncPost(this, '17030010', data);
      message.success(res.errorMessage || '状态更新成功');
      if (res.errorCode === '0') {
        this.getApplicationList();
        this.handleReset();
      }
    } catch (error) {
      console.log(error);
    }
  }

  // 判断内容是否修改
  whetherTheContentIsModified = () => {
    const { leftRowData, rightRowData } = this.state;
    let leftValues = this.leftEyeFormRef && this.leftEyeFormRef.getFieldsValue();
    let rightValues = this.rightEyeFormRef && this.rightEyeFormRef.getFieldsValue();
    let leftFlag = false;
    if (leftValues && leftValues.product) { // 左眼
      for (var leftValKey in leftValues) {
        for (var leftRowKey in leftRowData) {
          if ((leftValKey === leftRowKey) && (leftValues[leftValKey] !== leftRowData[leftRowKey])) {
            leftFlag = true;
            break;
          }
        }
      }
    }
    let rightFlag = false;
    if (rightValues && rightValues.product) {
      for (var rightValKey in rightValues) {
        for (var rightRowKey in rightRowData) {
          if ((rightValKey === rightRowKey) && (leftValues[rightValKey] !== leftRowData[rightRowKey])) {
            rightFlag = true;
            break;
          }
        }
      }
    }
    return leftFlag && rightFlag ? 'all' : (leftFlag ? 'left' : (rightFlag ? 'right' : ''));
  }

  // 发送
  handleSend = () => {
    let modifyFlag = this.whetherTheContentIsModified();
    if (modifyFlag) {
      Modal.confirm({
        title: '确认发送提醒',
        content: (modifyFlag === 'left' ? '左眼' : (modifyFlag === 'left' ? '右眼' : '左/右眼')) + '参数内容改变，确认保存并发送订单？',
        okText: '是',
        cancelText: '否',
        onOk: () => {
          this.handleSave(() => this.handleModifyStatus('02'));
        },
        onCancel: () => { },
      });
    } else {
      this.handleModifyStatus('02');
    }
  }

  // 打印
  handlePrint = async () => {
    try {
      const { currentPatData } = this.state;
      if (!(currentPatData && currentPatData.admID)) return;
      let data = {
        params: [{
          admID: currentPatData?.admID || '',
          viewFlag: 'Y'
        }]
      }
      let res = await React.$asyncPost(this, '17030084', data);
      let dataArr = res?.result || [];
      dataArr && dataArr.map((item, i) => {
        $loadTemplate(item.template, item.printStr);
      })
    } catch (error) {
      console.log(error);
    }
  }

  // 缴预交款
  handleAdvancePayment = async () => {
    try {
      let { currentPatData, prePayAmt } = this.state;
      if (!prePayAmt) {
        message.warning('请输入预交金额！');
        return;
      }
      let data = {
        params: [{
          admID: currentPatData?.admID || '',
          patAmt: prePayAmt,
        }]
      }
      let res = await React.$asyncPost(this, '17030071', data);
      let url = res?.result || '';
      let splitUrl = url && url.indexOf('/') > -1 ? url.split('/') : '';
      let splitParams = splitUrl && splitUrl.length > 0 ? splitUrl[splitUrl.length - 1] : '';
      let processID = splitParams && splitParams.indexOf('^') > -1 ? splitParams.split('^')[0] : ''; // 进程ID
      this.weChatRef && this.weChatRef.modifyVisible(true, {
        patAmt: prePayAmt,
        qrUrl: url,
        processID
      })
    } catch (error) {
      console.log(error);
    }
  }

  // 优惠
  handleDiscount = () => {
    let { currentPatData } = this.state;
    this.setState({ discountVisible: true });
    this.discountChild && this.discountChild.medicalInformation(currentPatData?.admID);
  }

  // 供应商退回状态删除订单
  handleReturnedByTheSupplier = () => {
    Modal.confirm({
      title: '确认删除提醒',
      content: '当前订单患者已缴费，删除后订单作废，患者可到收费处退费',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleModifyStatus('08'),
      onCancel: () => { },
    });
  }

  // 产品子类过滤
  handleMedSubCatChange = (e) => {
    this.setState({ medSubCatID: e }, () => {
      this.getBrandData();
    })
  }

  // 打印押金条
  handleDepositSlipPrint = async () => {
    try {
      // let { currentApplicationID } = this.state;
      // let data = {
      //   params: [{
      //     requestID: currentApplicationID
      //   }]
      // }
      const { currentPatData } = this.state;
      if (!(currentPatData && currentPatData.admID)) return;
      let data = {
        params: [{
          admID: currentPatData?.admID || ''
        }]
      }
      let res = await React.$asyncPost(this, '17030083', data);
      let dataArr = res?.result || [];
      dataArr && dataArr.map((item, i) => {
        $loadTemplate(item.template, item.printStr);
      })
    } catch (error) {
      console.log(error);
    }
  }

  // 关闭优惠弹窗
  hideDiscountVisible = () => {
    const { selectData } = this.state;
    this.setState({ discountVisible: false }, () => {
      selectData?.applyflag !== 'Y' && this.getApplicationList('', 'N');
    })
  }

  render() {
    const { selectData, leftEyeFormData, rightEyeFormData, currentEyeCard, brandData, varietyID, applicationList, currentApplicationID, currentApplicationData, brandSelectedKeys, leftRowData, rightRowData, prePayAmt, varietiesVal,
      varietiesData, depositAmt, discountVisible, currentPatData, medSubCatID, optoSourceID, remark, fittingRemark
    } = this.state;
    return (
      <div className="glasses-matching-application-form">
        <div className="common-query-split-line" style={{ height: 6 }}></div>
        <Row>
          <Col span={19}>
            <div style={{ paddingRight: '6px', position: 'relative' }}>
              <Card
                size="small"
                className="gmaf-left-card gmaf-card"
                title={(
                  <div className="flex">
                    <div className="card-title-left-img">
                      <img src={iconListVisits} alt="" />
                      {currentApplicationID ? '正在编辑申请单' : '正在新增申请单'}
                    </div>
                  </div>
                )}
                extra={(
                  <>
                    {selectData?.paymentQRCode === 'Y' ? (
                      <Button
                        size="small"
                        type="primary"
                        style={{ marginRight: 12 }}
                        onClick={this.handleAdvancePayment}
                      >
                        缴预交款
                      </Button>
                    ) : ''}
                    <Button
                      size="small"
                      style={{ background: '#ff3399', color: '#fff', marginRight: 12, borderColor: '#ff3399' }}
                      onClick={this.handleDiscount}
                    >
                      优惠
                    </Button>
                    <Button
                      size="small"
                      style={{ marginRight: 12 }}
                      onClick={this.handleReset}
                    >
                      {currentApplicationID ? '取消' : '清空'}
                    </Button>
                    {currentApplicationData && (currentApplicationData.statusCode === '01' || currentApplicationData.statusCode === '10' || currentApplicationData.statusCode === '20') ? (
                      currentApplicationData.statusCode === '10' && (currentApplicationData.billStatusCode == 'P' || currentApplicationData.billStatusCode == 'PP') ? (
                        <Button
                          ghost
                          size="small"
                          type="danger"
                          style={{ marginRight: 12 }}
                          onClick={this.handleReturnedByTheSupplier}
                        >
                          删除
                        </Button>
                      ) : (
                        <Popconfirm title="删除后不可恢复，确定要删除吗?" onConfirm={() => this.handleModifyStatus('08')}>
                          <Button
                            ghost
                            size="small"
                            type="danger"
                            style={{ marginRight: 12 }}
                          >
                            删除
                          </Button>
                        </Popconfirm>
                      )
                    ) : (
                      <Button ghost disabled type="primary" size="small" style={{ marginRight: 12 }}>删除</Button>
                    )}
                    {currentApplicationData && (currentApplicationData.statusCode === '02') ? (
                      <Popconfirm title="撤回后不可恢复，确定要撤回吗?" onConfirm={() => this.handleModifyStatus('01')}>
                        <Button
                          ghost
                          size="small"
                          type="danger"
                          style={{ marginRight: 12 }}
                        >
                          撤回
                        </Button>
                      </Popconfirm>
                    ) : (
                      <Button ghost disabled type="primary" size="small" style={{ marginRight: 12 }}>撤回</Button>
                    )}

                    <Button
                      ghost
                      size="small"
                      type="primary"
                      style={{ marginRight: 12 }}
                      disabled={!(currentApplicationData && (currentApplicationData.statusCode === '01' || currentApplicationData.statusCode === '20'))}
                      onClick={this.handleSend}
                    >
                      {currentApplicationData?.statusCode === '20' ? '重新发送' : '发送'}
                    </Button>
                    <Button
                      ghost
                      size="small"
                      type="primary"
                      style={{ marginRight: 12 }}
                      onClick={this.handlePrint}
                    >
                      打印
                    </Button>
                    {selectData?.noPrintDeposit !== 'Y' ? (
                      <Button
                        ghost
                        size="small"
                        type="primary"
                        style={{ marginRight: 12 }}
                        // disabled={!currentApplicationID}
                        onClick={this.handleDepositSlipPrint}
                      >
                        打印押金条
                      </Button>
                    ) : ''}
                    <Button
                      ghost={!((currentApplicationData && (currentApplicationData.statusCode === '01' || currentApplicationData.statusCode === '20')) || !currentApplicationID)} // 保持样式统一
                      size="small"
                      type="primary"
                      onClick={() => this.handleSave('')}
                      disabled={!((currentApplicationData && (currentApplicationData.statusCode === '01' || currentApplicationData.statusCode === '20')) || !currentApplicationID)}
                    >
                      保存
                    </Button>
                  </>
                )}
              >
                <div>
                  <div style={{ marginBottom: '6px' }}>
                    {/* <span style={{ position: 'relative', padding: '4px 0 0 20px' }} className="formRequired">收款方式：</span>
                    <Select
                      showSearch
                      value={paymentMethod}
                      placeholder="请选择"
                      optionFilterProp="search"
                      style={{ width: '100px' }}
                      onChange={e => this.setState({ paymentMethod: e })}
                    >
                      {React.$SelectOptions([])}
                    </Select> */}
                    <span className="formRequired common-input-label" style={{ position: 'relative', padding: '4px 0 0 20px' }}>预交金额：</span>
                    <Input
                      type="number"
                      value={prePayAmt}
                      placeholder="请输入金额"
                      className="input-number"
                      style={{ width: '120px' }}
                      onChange={e => this.setState({ prePayAmt: e.target.value })}
                    />
                    <span style={{ position: 'relative', padding: '4px 0 0 20px' }} className={[selectData?.channelSourceNotMust !== 'Y' ? 'formRequired' : '', 'common-input-label'].join(' ')}>验配渠道：</span>
                    <Select
                      allowClear
                      showSearch
                      value={optoSourceID}
                      placeholder="请选择"
                      optionFilterProp="search"
                      style={{ width: '120px', marginRight: '6px' }}
                      onChange={e => this.setState({ optoSourceID: e })}
                    >
                      {React.$SelectOptions(selectData?.optoSource || [])}
                    </Select>
                    <Input
                      value={remark}
                      placeholder="请输入备注内容"
                      style={{ width: '160px', marginRight: '12px' }}
                      onChange={e => this.setState({ remark: e.target.value })}
                    />
                    <span className="common-input-label">开单备注：</span>
                    <Input
                      value={fittingRemark}
                      placeholder="请输入备注内容"
                      style={{ width: '160px' }}
                      onChange={e => this.setState({ fittingRemark: e.target.value })}
                    />
                    {/* 建议预交金额：
                    <Tag
                      style={{ borderColor: '#007AFF', background: '#fff', color: '#007AFF', cursor: 'pointer' }}
                      onClick={this.handleSetPrePayAmt}
                    >
                      {((Number((leftRowData?.varietiesRecord?.price || 0)).toFixed(3)) * 1000 + (Number((rightRowData?.varietiesRecord?.price || 0)).toFixed(3)) * 1000) / 1000}
                    </Tag> */}
                    <div style={{ float: 'right', height: '32px', paddingRight: '10px' }} className="flex-align-items">
                      <span className="common-input-label">视光账户余额：</span>
                      <strong style={{ color: '#fa8c17' }}>{depositAmt}</strong>元
                    </div>
                  </div>
                  <Row>
                    <Col span={14}>
                      <Card
                        type="inner"
                        size="small"
                        className="gmaf-children-card gmaf-children-card-first"
                        title={<div className="card-title-left-icon"><div></div>配镜参数</div>}
                        extra={(
                          <span style={{ color: '#bbb', fontSize: '12px', display: selectData?.splitNoteFlag === 'N' ? 'none' : 'inline-block' }}>
                            {selectData?.splitNote || '注释：保存双眼会拆分成两个申请单。'}
                          </span>
                        )}
                      >
                        <div className="flex gmaf-children-card-context scroll-bar-style" style={{ height: store.getState().tableHeight.y + 43 }}>
                          <div
                            className={(currentEyeCard === 'right' ? 'gmaf-current-eye-card' : '') + ' gmaf-eye-card'}
                            onClick={() => this.handleEyeCardClick('right', 'click')}
                          >
                            <div style={{ padding: '0 12px' }}>
                              <div className="flex-between-center" style={{ borderBottom: '1px solid #e8e8e8', width: '100%', padding: '6px 0' }}>
                                <span className="span" style={{ fontSize: '14px' }}>右眼(OD)</span>
                                <div>
                                  <Button
                                    ghost
                                    type="danger"
                                    size="small"
                                    disabled={!(currentEyeCard === 'right')}
                                    style={{ color: currentEyeCard === 'right' ? 'red' : '' }}
                                    onClick={this.handleRightFormReset}
                                  >清空</Button>
                                  {currentApplicationID ? '' : (
                                    <>
                                      <Button
                                        size="small"
                                        type="primary"
                                        style={{ marginLeft: '12px' }}
                                        onClick={this.handleSameLeftEye}
                                      >
                                        同左眼
                                      </Button>
                                    </>
                                  )}
                                </div>
                              </div>
                            </div>
                            <div style={{ padding: '6px', paddingLeft: '0', position: 'relative', height: 'calc(100% - 36px)' }}>
                              <div className="scroll-bar-style" style={{ height: '100%', overflow: 'auto' }}>
                                <DynamicRenderingForm
                                  className="gmaf-dynamic-form"
                                  rowData={rightRowData}
                                  formData={rightEyeFormData}
                                  formItemCol={{ labelCol: 9, wrapperCol: 14, col: 24 }}
                                  onRef={ref => this.rightEyeFormRef = ref}
                                />
                                <div className="no-matching-data" style={{ display: rightEyeFormData && rightEyeFormData.length > 0 ? 'none' : 'block' }}>
                                  暂无配镜信息
                                </div>
                              </div>
                            </div>
                          </div>
                          <div style={{ width: '10px' }}></div>
                          <div
                            className={(currentEyeCard === 'left' ? 'gmaf-current-eye-card' : '') + ' gmaf-eye-card'}
                            onClick={() => this.handleEyeCardClick('left', 'click')}
                          >
                            <div style={{ padding: '0 12px' }}>
                              <div className="flex-between-center" style={{ borderBottom: '1px solid #e8e8e8', width: '100%', padding: '6px 0' }}>
                                <span className="span" style={{ fontSize: '14px' }}>左眼(OS)</span>
                                <div>
                                  <Button
                                    ghost
                                    type="danger"
                                    size="small"
                                    disabled={!(currentEyeCard === 'left')}
                                    // style={{ color: currentEyeCard === 'left' ? 'red' : '' }}
                                    onClick={this.handleLeftFormReset}
                                  >
                                    清空
                                  </Button>
                                  {currentApplicationID ? '' : (
                                    <>
                                      <Button
                                        size="small"
                                        type="primary"
                                        style={{ marginLeft: '12px' }}
                                        onClick={this.handleSameRightEye}
                                      >
                                        同右眼
                                      </Button>
                                    </>
                                  )}
                                </div>
                              </div>
                            </div>
                            <div style={{ padding: '6px', paddingLeft: '0', position: 'relative', height: 'calc(100% - 36px)' }}>
                              <div className="scroll-bar-style" style={{ height: '100%', overflow: 'auto' }}>
                                <DynamicRenderingForm
                                  className="gmaf-dynamic-form"
                                  rowData={leftRowData}
                                  formData={leftEyeFormData}
                                  formItemCol={{ labelCol: 9, wrapperCol: 14, col: 24 }}
                                  onRef={ref => this.leftEyeFormRef = ref}
                                />
                                <div className="no-matching-data" style={{ display: leftEyeFormData && leftEyeFormData.length > 0 ? 'none' : 'block' }}>
                                  暂无配镜信息
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </Card>
                    </Col>
                    <Col span={3}>
                      <div style={{ paddingLeft: '6px', position: 'relative' }}>
                        <Card
                          type="inner"
                          size="small"
                          className="gmaf-children-card gmaf-children-card-center"
                          title={<div className="card-title-left-icon"><div></div>品牌选择</div>}
                        >
                          <Select
                            allowClear
                            showSearch
                            value={medSubCatID}
                            placeholder="请选择"
                            optionFilterProp="search"
                            style={{ width: '100%', marginBottom: '4px', paddingRight: 12 }}
                            onChange={this.handleMedSubCatChange}
                          >
                            {React.$SelectOptions(selectData?.stkSubCatID || [])}
                          </Select>
                          <div
                            style={{
                              width: '100%',
                              overflow: 'auto',
                              paddingRight: 12,
                              height: store.getState().tableHeight.y - 17,
                            }}
                          >
                            <Menu
                              style={{ width: '100%' }}
                              selectedKeys={brandSelectedKeys}
                              onSelect={this.handleBrandMenuSelect}
                            >
                              {brandData && brandData.map(item => {
                                return (
                                  <Menu.Item key={item.brandID} disabled={!!currentApplicationID} title={item.brandDesc}>
                                    {item.brandDesc}
                                  </Menu.Item>
                                )
                              })}
                            </Menu>
                          </div>
                        </Card>
                        <div className="common-card-left-split-line" style={{ width: 6, background: '#fff' }}></div>
                      </div>
                    </Col>
                    <Col span={7}>
                      <Card
                        type="inner"
                        size="small"
                        className="gmaf-children-card gmaf-children-card-right"
                        title={<div className="card-title-left-icon"><div></div>产品选择</div>}
                        extra={(
                          <Input
                            placeholder="请输入名称后回车查询"
                            style={{ width: '100%' }}
                            className="gmaf-varieties-search"
                            disabled={!!currentApplicationID}
                            value={varietiesVal}
                            onChange={e => this.setState({ varietiesVal: e.target.value })}
                            onPressEnter={() => this.getBrandData('N')}
                          />
                        )}
                      >
                        <div style={{ paddingRight: 6 }}>
                          <div
                            style={{
                              overflow: 'auto',
                              width: '100%',
                              height: store.getState().tableHeight.y + 19,
                            }}
                            className="gmaf-children-card-right-radio scroll-bar-style"
                          >
                            <Radio.Group
                              value={varietyID}
                              onChange={this.handleVarietiesChange}
                            >
                              {varietiesData && varietiesData.map((item, index) => {
                                return (
                                  <Radio style={{ width: 'calc(100% - 16px)' }} className="gmaf-children-card-right-radio-items" disabled={!!currentApplicationID} key={index} value={item.medID}>
                                    <div className="ellipsis" style={{ maxWidth: '100%' }} title={item.medDesc}>{item.medDesc}</div>
                                    <div style={{ paddingLeft: '12px' }}><span style={{ color: '#1999db', fontWeight: 'normal', fontSize: '13px' }}>{item?.price || '0'}元/{item?.unitDesc || ''}</span></div>
                                  </Radio>
                                )
                              })}
                            </Radio.Group>
                          </div>
                        </div>
                      </Card>
                    </Col>
                  </Row>
                </div>
              </Card>
              <div className="common-card-right-split-line" style={{ width: 6 }}></div>
            </div>
          </Col>
          <Col span={5}>
            <Card
              size="small"
              className="gmaf-card gmaf-application-list"
              title={(
                <div className="flex">
                  <div className="card-title-left-img">
                    <img src={iconListVisits} alt="" />
                    申请单列表
                  </div>
                </div>
              )}
            >
              <div id="gmaf-application-list-content" className="gmaf-application-list-content scroll-bar-style" style={{ height: store.getState().tableHeight.y + 132, overflow: 'auto' }}>
                {applicationList && applicationList.length > 0 ? applicationList.map((item, index) => {
                  return (
                    <div
                      key={index}
                      className={(currentApplicationID === item.glassesRequestID ? 'gmaf-application-list-item-active' : '') + ' gmaf-application-list-item'}
                      onClick={() => this.handleApplicationListItemClick(item)}
                    >
                      <div className="gmaf-application-list-header flex-align-items">
                        <Tag color={item.statusDesc === '待发送' ? '#f50' : (item.statusDesc === '已取镜' ? '#007AFF' : '')}>{item.statusDesc}</Tag>
                        <div className="gmaf-application-list-header-title ellipsis" title={item?.titleDesc || ''}>
                          {'urgentSign' in item && item.urgentSign && item.urgentSign !== '无' ? <span style={{ color: '#e40a0a', fontSize: '12px' }}>{'('}{item.urgentSign}{')'}</span> : ''}
                          {item?.titleDesc || ''}
                        </div>
                      </div>
                      <Row>
                        <Col span={18} className="gmaf-application-list-item-content">
                          <p className="ellipsis"><span>开单时间：</span><span title={item.createDateTime}>{item.createDateTime}</span></p>
                          <p className="ellipsis">
                            <span>订单金额：</span>
                            <span style={{ color: '#fa8c17' }}>{item?.orderAmt || 0}</span>
                            <span style={{
                              color: '#fa8c17',
                              textDecoration: 'line-through',
                              marginLeft: '4px',
                              display: (Number(item?.orderAmt || 0) !== Number(item?.totalAmt || 0)) || selectData?.totalAmtFlag === 'Y' ? 'inline-block' : 'none'
                            }}>
                              {'('}原价{item?.totalAmt || 0}{')'}
                            </span>
                          </p>
                          <p className="ellipsis"><span>执行科室：</span><span title={item.locDesc}>{item.locDesc}</span></p>
                        </Col>
                        <Col span={6} className="flex-center" style={{ height: '96px' }}>
                          <div
                            className={item.billStatusCode == 'P' || item.billStatusCode == 'PP' ? 'charge-status-check' : 'charge-status-uncheck'}
                            style={{ position: 'relative', height: '62px', textAlign: 'center', backgroundPosition: item.billStatusCode == 'P' || item.billStatusCode == 'PP' ? '-20px -110px' : '-20px -180px' }}
                          >
                          </div>
                        </Col>
                      </Row>
                    </div>
                  )
                }) : (
                  <div style={{ marginTop: '120px' }}>
                    <Empty />
                  </div>
                )}
              </div>
            </Card>
          </Col>
        </Row>
        <WeChatPayment handleQuery={this.getApplicationList} onRef={ref => this.weChatRef = ref} />
        <Modal
          title="优惠折扣"
          className='discount-modal'
          visible={discountVisible}
          onCancel={this.hideDiscountVisible}
          footer={false}
        >
          <PatientAdmOrderCharges
            remarksRequiredFlag={selectData?.remarksRequiredFlag || 'Y'}
            selectData={selectData}
            admID={currentPatData?.admID}
            patID={currentPatData?.patID}
            userInfo={currentPatData}
            applyflag={selectData?.applyflag || 'N'}
            onRef={ref => this.discountChild = ref}
            closeModal={this.hideDiscountVisible}
          />
        </Modal>
      </div>
    )
  }
};

export default GlassesMatchingApplicationForm;